<template>
  <div class="user-profile">
    <!-- 返回首页按钮 -->
    <div class="back-home">
      <el-button type="primary" @click="$router.push('/')" plain>
        <el-icon><House /></el-icon>
        返回首页
      </el-button>
    </div>

    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" link @click="handleEdit">
            编辑资料
          </el-button>
        </div>
      </template>
      <div class="user-info">
        <div class="avatar-wrapper">
          <el-avatar :size="100" :src="userInfo.avatar" />
          <div class="avatar-upload">
            <el-upload
                class="upload-btn"
                action="http://localhost:9011/api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders"
                name="file"
                accept=".jpg,.jpeg,.png"
            >
              <el-button type="primary" link>更换头像</el-button>
            </el-upload>
          </div>
        </div>
        <div class="info-content">
          <h3 class="nickname">{{ userInfo.nickname || userInfo.username }}</h3>
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱：</span>
            <span class="value">{{ userInfo.email || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span class="value">{{ userInfo.gender === 1 ? '男' : userInfo.gender === 2 ? '女' : '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ formatDateTime(userInfo.createTime) }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
        title="编辑个人信息"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/api/user'
import dayjs from 'dayjs'
import { getToken } from '@/utils/auth'
import { House } from '@element-plus/icons-vue'

const userInfo = ref({})
const dialogVisible = ref(false)
const formRef = ref(null)

// 上传相关配置
const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`
}

const form = ref({
  nickname: '',
  gender: null,
  phone: '',
  email: ''
})

const rules = {
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm:ss') : '未知'
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo()
    userInfo.value = res.data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 处理编辑
const handleEdit = () => {
  form.value = { ...userInfo.value }
  dialogVisible.value = true
}

// 处理提交编辑
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    await updateUserInfo({
      id: userInfo.value.id,  // 确保包含用户ID
      ...form.value
    })
    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchUserInfo()
  } catch (error) {
    if (error === false) return  // 表单验证失败
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2


  return true
}

// 头像上传成功的回调
const handleAvatarSuccess = async (res) => {
  try {
    if (res.code === 200) {
      await updateUserInfo({
        id: userInfo.value.id,
        nickname: userInfo.value.nickname,
        gender: userInfo.value.gender,
        phone: userInfo.value.phone,
        email: userInfo.value.email,
        avatar: res.data
      })
      ElMessage.success('头像更新成功')
      fetchUserInfo()
    } else {
      throw new Error(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error(error.message || '头像更新失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped lang="scss">
.user-profile {
  padding: 20px;
}

.back-home {
  margin-bottom: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  text-align: center;

  .avatar-wrapper {
    position: relative;
    display: inline-block;
    margin-bottom: 20px;

    .avatar-upload {
      margin-top: 10px;
    }
  }

  .info-content {
    .nickname {
      margin: 0 0 20px;
      font-size: 24px;
      color: #303133;
    }

    .info-item {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 12px 0;
      color: #666;

      .label {
        width: 100px;
        text-align: right;
        margin-right: 15px;
        color: #909399;
      }

      .value {
        text-align: left;
        color: #303133;
      }
    }
  }
}
</style>
